package com.aiden.app.common.widget.glide

import android.content.Context
import android.graphics.*
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.TransformationUtils
import java.security.MessageDigest

/**
 * Glide圆角转换
 *
 * @author yanggeng
 * @date 2019/1/24 下午1:28
 */
class GlideRoundTransform(var context: Context, var radius : Float = 10f) : BitmapTransformation() {

    private val ID = "com.dahu.app.common.widget.glide.GlideRoundTransform"

    override fun updateDiskCacheKey(digest: MessageDigest) {
        digest.update(ID.toByteArray(Key.CHARSET))
    }

    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
        val bitmap = TransformationUtils.centerCrop(pool, toTransform, outWidth, outHeight)
        return roundCrop(pool, bitmap)
    }

    override fun equals(other: Any?): Boolean {
        if (other is GlideRoundTransform) {
            return this === other
        }
        return false
    }

    override fun hashCode(): Int {
        return ID.hashCode()
    }

    private fun roundCrop(pool: BitmapPool, bitmap: Bitmap): Bitmap {
        val result = pool.get(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(result)
        val paint = Paint()
        paint.shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        paint.isAntiAlias = true
        val rectF = RectF(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat())
        canvas.drawRoundRect(rectF, radius, radius, paint)
        return result
    }
}